<template>
  <div style="width: 100%; height: 100%">

    <vxe-grid ref="tableRef" v-bind="gridOptions" :data="dataList">
      <template #toolbar_buttons>
        <Button type="primary" size="small" @click="handleCreate">新增</Button>

        <Button type="primary" size="small" class="m-3" @click="selectGroupShowFn">导入excel</Button>
        <Button @click="aoaToExcel" size="small"> 模版下载 </Button>
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="[
          {
              label:'修改',
              onClick: handleEdit.bind(null, row),
          },
           {
              label:'删除',
              color: 'error',
              loading: row.loading,
              popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, row),
                },
             },
        ]
        " />
      </template>

    </vxe-grid>
    <FormModal @register="register" @success="handleSuccess" />

    <Modal v-model:visible="applyViewShow" title="导入信息有误" @ok="applyViewClose">
      <div>
        <p v-for="(item, index) in msgList">{{ item }} </p>
      </div>
    </Modal>

<!--    选择小组弹层-->
    <Modal v-model:visible="selectGroupShow" title="选择车间小组后再导入" :footer="null">
      <vxe-form
        :data="formData"
        size="small"
        @submit="submitEvent"
        @reset="resetEvent">

        <vxe-form-item title="车间小组" field="groupId" span="24" :item-render="{}">
          <template #default="params">
            <vxe-select v-model="formData.groupId" placeholder="请选择" clearable :default-value="kqDeptSelectObj.groupId">
              <vxe-option :value="item.id" :label="item.groupName"  v-for="(item,index) in kqDeptSelectObj.list"></vxe-option>
<!--              <vxe-option value="车间人员" label="车间人员"></vxe-option>-->
            </vxe-select>
          </template>
        </vxe-form-item>


        <vxe-form-item  span="24" :item-render="{}">
          <template #default>
            <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
              <vxe-button :loading="loading" status="primary" content="导入Excel" >  </vxe-button>
            </ImpExcel>
          </template>
        </vxe-form-item>
      </vxe-form>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
import {
  BasicTableProps,
  VxeGridInstance,
  VxeTableDefines,
} from '@/components/VxeTable';
import { aoaToSheetXlsx, jsonToSheetXlsx } from '@/components/Excel';

import { BasicTable, useTable, TableAction } from '@/components/Table';

import { useDrawer } from '@/components/Drawer';

import {onMounted, reactive, ref} from 'vue';

import FormModal from './FormModal.vue';

import { vxeTableColumns,vxeTableFormSchema } from './role.data';
import { useMessage } from "@/hooks/web/useMessage";
import {Button, Modal} from 'ant-design-vue';
import { useGo } from "@/hooks/web/usePage";
import {ImpExcel} from "@/components/Excel";
import { kqUserList,importKqUser,removeKqUser,kqDeptSelect } from '@/api/heng/production';

const go = useGo();

defineOptions({ name: 'ywDeptList' });
const { createMessage } = useMessage();

// const [register, { openModal, closeModal }] = useModal();
const [register, { openDrawer,closeDrawer }] = useDrawer();

const loading=ref(false);
const msgList = ref([]);
const applyViewShow = ref(false);
const selectGroupShow = ref(false);//选择小组
const kqDeptSelectObj=ref({
  groupId:"",
  list:[]
});//下拉选择小组

const formData=ref({
});

const dataList=ref([]);
const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig:{},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    print:false,
    export:false,
    refresh:false,
    custom:false,
    zoom:false,
    // refresh: true,
    // enabled:false
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field ] = value;
    });
  }
  return kqUserList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}


function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

onMounted(() => {
  kqDeptSelectFn();
})


function handleEdit(record: Recordable) {
  record.isUpdate=true;
  openDrawer(true, record);

}



function handleDelete(record: Recordable) {
  record.loading = true;
  removeKqUser({userId: record.userId})
    .then((res) => {
    if (res.code == 200) {
      createMessage.success(res.message);
      tableRef.value.commitProxy('reload');
    } else {
      createMessage.error(res.message);
    }
  }).catch((res) => {
      createMessage.error(res.message);
  }) .finally(() => {
      record.loading = false;
  });
}

function handleSuccess() {
  tableRef.value.commitProxy('query');

}


function applyViewOpen() {
  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}

//选择小组
function submitEvent({data}) {
  // console.log("--submitEvent:",data);
}
function resetEvent(e){

}

//
function selectGroupShowFn(){
  selectGroupShow.value = true;
}

function kqDeptSelectFn(){
  kqDeptSelect().then(res=>{
    if (res.code == 200) {
      kqDeptSelectObj.value = res.data;
    }else {
      createMessage.error(res.message);
    }
  })
}


/**
 * 导入excel
 * key 为实体类字段
 * value excel列中文名称
 * "费用名称","金额","供应商名称","真实物料编号(逗号隔开)","开始日期","退款条件类型","退款条件数量","经办人"
 */
const arrHeader = [

  {
    key: 'userName',
    value: '姓名',
  },
  {
    key: 'izLianBanTxt',
    value: '是否连班',
  },

];

function getHeadArr() {
  let arr = [];
  arrHeader.forEach((r) => {
    arr.push(r.value);
  });
  return arr;
}

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  let list = [];
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      arrHeader.forEach((e) => {
        if (e.value == key) {
          json[e.key] = r[key];
        }
      });
    }

    data.list.push(json);
  });
  return data;
}

function excelSuccessFn(list) {
  console.log("---formData.value.groupId:",formData.value.groupId)
  if(!formData.value.groupId){
    createMessage.error("请选择车间小组!")
    return;
  }

  let results = list[0].results;
  let data = changeSubmitArr(results);

  loading.value = true;
  let obj={list:data.list,groupId:formData.value.groupId};
  importKqUser(obj ).then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          // let msg="";
          // for(let i=0;i<res.data.length;i++){
          //   let row= res.data[i];
          //   msg+=`第${row.index}行 ${row.message}\n`
          // }
          msgList.value = res.data;
          selectGroupShow.value = false;

          // visible.value = true;
          applyViewOpen();
        } else {
          selectGroupShow.value = false;

          createMessage.success('导入成功!');
          tableRef.value.commitProxy('reload');
        }
      } else {
        loading.value = false;
        selectGroupShow.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}
function aoaToExcel() {
  // 保证data顺序与header一致
  let arrHeader=[ "姓名","是否连班"];
  aoaToSheetXlsx({
    data: [],
    header: arrHeader,
    filename: '车间考勤人员导入模版.xlsx',
  });

  // window.open('http://220.161.77.66:10111/app_file/excel/迪卡侬映射产品导入.xls');
}

</script>
